import { createRouter, createWebHashHistory } from "vue-router";

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    component: () => import("../views/Home.vue"),
    children: [
      {
        path: "/home",
        redirect: "/home/index",
      },
      {
        path: "/home/index",
        component: () => import("../views/Home/Index.vue"),
      },
      {
        path: "/home/questions",
        component: () => import("../views/Home/Questions.vue"),
      },
      {
        path: "/home/consult",
        component: () => import("../views/Home/Consult.vue"),
      },
      {
        path: "/home/message",
        component: () => import("../views/Home/Message.vue"),
        meta: { requireLogin: true },
      },
      {
        path: "/home/mine",
        component: () => import("../views/Home/Mine.vue"),
      },
    ],
  },
  {
    path: "/detail/:id",
    component: () => import("../views/Detail.vue"),
  },
  {
    path: "/registry",
    component: () => import("../views/Registry.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/class",
    component: () => import("../views/Class.vue"),
    children: [
      {
        path: "/class",
        redirect: "/class/xinli",
      },

      {
        path: "/class/xinli",
        component: () => import("../views/Class/xinli.vue"),
      },
      {
        path: "/class/specialClass",
        component: () => import("../views/Class/specialCalss.vue"),
      },
    ],
  },
  {
    path: "/test",
    component: () => import("../views/Index/Test.vue"),
  },
  {
    path: "/talking",
    component: () => import("../views/Index/Talking.vue"),
  },
  {
    path: "/radio",
    component: () => import("../views/Index/Radio.vue"),
  },
  {
    path: "/article",
    component: () => import("../views/Index/Article.vue"),
  },
  {
    path: "/talk",
    component: () => import("../views/Talk.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("../views/404NotFound.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});
router.beforeEach((to, from, next) => {
  if (to.meta.requireLogin) {
    if (localStorage.getItem("tokenstring")) {
      next();
    } else {
      localStorage.setItem("path", to.path);
      next({ name: "Login" });
    }
  } else {
    next();
  }
});

export default router;
